from CommandWriter import *
from StateReader import *
from LifeLike import *
#from ReadFlags import *
from tkinter import *
from tkinter.filedialog import askopenfilename
import os
import subprocess
import threading
import operator
import time

def StartGUI(root, ruleNum):
	
	cellularGui = None
	
	if ruleNum == 1:
		cellularGui = LifeLike(root)
	
	pollThread = threading.Thread(target=PollForUpdates, args=[cellularGui])
	pollThread.setDaemon(True)
	pollThread.start()
	
	root.update()
	root.deiconify()
	root.mainloop()

def PollForUpdates(cellularGui):
	
	filename = "statefile.txt"
	import pdb; pdb.set_trace()
	while True:

		if os.path.isfile(filename) == True:
			updates = ReadFile(filename)
			coords = ParseState(updates)
		
			for coord in coords:
				cellularGui.handleACL2Coordinate(coord)
				
			DeleteFile(filename)
	
def main():
	root = Tk()
	root.withdraw()
	
	filename = askopenfilename(title="Select a Rule set", filetypes=[("XML", ".xml")])
	WriteConfigFilename(filename)
	
	subprocess.Popen("build.exe")
	
	ruleNum = None
	while (True):
		if os.path.isfile("ruletype.txt"):
			rule = ReadFile("ruletype.txt")
			rule = operator.itemgetter(0)(rule)
			if rule == "elementary":
				ruleNum = 0
			elif rule == "lifelike":
				ruleNum = 1
			break
		time.sleep(100)
	
	StartGUI(root, ruleNum)

if __name__ == '__main__':
	main()
